package com.mes.service.impl;


import com.mes.constant.ResponseStatus;
import com.mes.mapper.BaseMapper;
import com.mes.mapper.PrivilegeMapper;
import com.mes.mapper.RolePrivilegeMapper;
import com.mes.mapper.UserRoleMapper;
import com.mes.po.Privilege;
import com.mes.po.RolePrivilege;
import com.mes.po.UserRole;
import com.mes.service.IPrivilegeService;
import com.mes.util.MesResponse;
import com.mes.vo.UserPriviligers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
public class PrivilegeServiceImpl extends BaseServiceImpl<Privilege> implements IPrivilegeService {

    @Autowired
    private PrivilegeMapper privilegeMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RolePrivilegeMapper rolePrivilegeMapper;

    @Override
    BaseMapper<Privilege> getMapper() {
        return privilegeMapper;
    }

    @Override
    public List<Privilege> selectPrivileges() {
        return privilegeMapper.selectAllPrivileges();
    }

    @Override
    public UserPriviligers getPrivilegesByUserId(Integer userId) {

        UserPriviligers userPrivileges = new UserPriviligers();

        // 查询所有权限
        List<UserRole> roleList = userRoleMapper.selectByUserId(userId);
        List<Privilege> allPrivilegeList = new ArrayList<>();
        for(UserRole userRole : roleList){
            List<RolePrivilege> rolePrivilegeList =  rolePrivilegeMapper.selectByRoleId(userRole.getRoleId());
            for(RolePrivilege rolePrivilege : rolePrivilegeList){
                Privilege privilege = privilegeMapper.selectByPrimaryKey(rolePrivilege.getPrivilegeId());
                allPrivilegeList.add(privilege);
            }
        }

        // 转格式输出
        List<Privilege> privileges = new ArrayList<>();
        Map<String,List<Privilege>> privilegeMap = new HashMap<>();
        for(Privilege privilege : allPrivilegeList){
            if(privilege.getParentId() == 0){
                privileges.add(privilege);
            }else{
                if(privilegeMap.containsKey(privilege.getParentId().toString())){
                    privilegeMap.get(privilege.getParentId().toString()).add(privilege);
                }else{
                    List<Privilege> privilegeList = new ArrayList<>();
                    privilegeList.add(privilege);
                    privilegeMap.put(privilege.getParentId().toString(),privilegeList);
                }
            }

        }
        userPrivileges.setPrivileges(privileges);
        userPrivileges.setPrivilegeMap(privilegeMap);
        return userPrivileges;
    }
}
